package com.rongshu.widget.xrichtext;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;

import com.rongshu.R;
import com.utils.DensityUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yinshuai on 2017/8/14.
 *
 * @author yinshuai
 */
public class EditTextPlus extends AppCompatEditText {
    //剔除图片后的文本字符串
    private String submitCon = "";
    //插入图片监听
    private OnInsertionImageListener onInsertionImageListener;
    //删除图片监听
    private OnDeleteConteneListener onDeleteConteneListener;

    private float startY;
    private float startX;
    //拼接在图片之前的字符串(方便后台识别图片)
    public static String article_start_label = "<div><br/></div><img";
    //拼接在图片之后的字符串(方便后台识别图片)
    public static String article_end_label = "\"/><div><br/></div>";
    //插入内容中的图片集合
    private List<String> image = new ArrayList<>();

    public EditTextPlus(Context context) {
        super(context);
        init();
    }

    public EditTextPlus(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void init() {
        setGravity(Gravity.TOP);
        addTextChangedListener(watcher);
    }

    public interface OnInsertionImageListener {
        /**
         * 插入图片时的监听
         */
        void insertion();
    }

    public void setOnInsertionImageListener(OnInsertionImageListener onInsertionImageListener) {
        this.onInsertionImageListener = onInsertionImageListener;
    }

    public interface OnDeleteConteneListener {
        /**
         * 删除图片的监听
         */
        void delete();
    }

    public void setOnDeleteConteneListener(OnDeleteConteneListener onDeleteConteneListener) {
        this.onDeleteConteneListener = onDeleteConteneListener;
    }

    public void insertIndexImg(String url, Bitmap bitmap) {
        CharSequence sequence = getDrawableStrForBitmap(url, bitmap);
        Editable editable = getText();
        editable.insert(getSelectionStart(), sequence);
        editable.insert(getSelectionStart(), "\n");
        //让光标始终在最后
        this.setSelection(getText().toString().length());
        if (onInsertionImageListener != null) {
            onInsertionImageListener.insertion();
        }
    }

    /**
     * 获取插入的图片列表
     *
     * @return
     */
    public List<String> getImage() {
        return image;
    }


    /**
     * 获取去除image后的文字内容
     */
    public String getTextContent() {
        return submitCon;
    }

    /**
     * 获取全部内容
     */
    public String getAllContent() {
        return getText().toString();
    }


    private String tempString;
    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //如果小于就是删除操作
            if (s.length() < tempString.length()) {
                String deletString = tempString.substring(start, start + before);
                if (image != null && image.size() > 0) {
                    for (int i = 0; i < image.size(); i++) {
                        //如果删除的内容中包含这张图片 那么就把图片集合中的对应的图片删除
                        if (deletString.contains(image.get(i))) {
                            image.remove(image.get(i));
                            if (onDeleteConteneListener != null) {
                                onDeleteConteneListener.delete();
                            }
                        }
                    }
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            tempString = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s) {
            invalidate();
            requestLayout();

            //------------------此步骤主要为获取剔除图片后的，文本内容--------------
            StringBuffer stringBuffer = new StringBuffer(getText().toString());
            for (int i = 0; i < image.size(); i++) {
                if (stringBuffer.indexOf(image.get(i)) != -1) {
                    int index = stringBuffer.indexOf(image.get(i));
                    stringBuffer.delete(index, index + image.get(i).length());
                    stringBuffer.insert(index, "");
                }
            }
            submitCon = stringBuffer.toString();
            //----------------------------------------------------------------
        }


    };

    /**
     * 编辑插入的内容
     */
    private CharSequence getDrawableStrForBitmap(String url, Bitmap bitmap) {
//        String str = "<img" + " " + "src=\"" + url + "\"/>";
        String str = article_start_label + " " + "src=\"" + url + article_end_label;
        image.add(str);
        final SpannableString ss = new SpannableString(str);
        // 定义插入图片
        Drawable drawable = new BitmapDrawable(getResources(), bitmap);

        float scenewidth = DensityUtil.getScreenWidth(getContext());
        float width = drawable.getIntrinsicWidth();
        float height = drawable.getIntrinsicHeight();
        float scale = (scenewidth) / width;
        width *= scale;
        height *= scale;
        if (width >= scenewidth) {
            width = width - getResources().getDimension(R.dimen.dd_dimen_60px);
            height = height - getResources().getDimension(R.dimen.dd_dimen_60px);
        }
        //设置图片的宽高
        drawable.setBounds(2, 0, (int) width, (int) height);
        //ALIGN_BOTTOM 调整图片距离字有一定的间隙
        VerticalCenterImageSpan span = new VerticalCenterImageSpan(drawable, 1);
        //SPAN_INCLUSIVE_EXCLUSIVE 会导致删除后面的文字消失
        ss.setSpan(span, 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return ss;
    }

    public class VerticalCenterImageSpan extends ImageSpan {

        public VerticalCenterImageSpan(Drawable d, int verticalAlignment) {
            super(d, verticalAlignment);
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            Drawable b = getDrawable();
            canvas.save();

            int transY = bottom - b.getBounds().bottom;
            if (mVerticalAlignment == ALIGN_BASELINE) {
                transY -= paint.getFontMetricsInt().descent;
            } else if (mVerticalAlignment == ALIGN_BOTTOM) {

            } else {
                transY += paint.getFontMetricsInt().descent * 2;
            }

            canvas.translate(x, transY);
            b.draw(canvas);
            canvas.restore();
        }
    }

    /**
     * 重写dispatchTouchEvent是为了解决上下滑动时光标跳跃的问题
     *
     * @param event
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startY = event.getRawY();
                startX = event.getRawX();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                float endY = event.getRawY();
                float endX = event.getRawX();

                if (Math.abs(endY - startY) > 10 || Math.abs(endX - startX) > 10) {
                    return true;
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }
}
